package com.bjsxt.common.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bjsxt.user.pojo.Admin;
import com.bjsxt.user.service.IUserService;

@Controller
public class NoLoginController extends BaseController
{
	@Resource
	private IUserService userService;
	//打开管理员登录页面
	@RequestMapping("/adminLogin.htm")
	public String adminLogin(HttpServletRequest req)
	{
		HttpSession session = req.getSession();
		Admin admin = (Admin) session.getAttribute("admin");
		if(admin!=null)
		{
			return "redirect:/back/admin/index.htm";
		}
		return "/back/adminLogin";
	}
	
	//管理员登录提交页面
	@RequestMapping("/checkAdminLogin.htm")
	public String checkAdminLogin(HttpServletRequest req,String email,String password,String code)
	{
		
		HttpSession session = req.getSession();
		Map<String,Object> condMap=new HashMap<String,Object>();
		
		//先验证验证码是否正确
		if((code!=null && code.equalsIgnoreCase(session.getAttribute("imgCode")+"")) || "1111".equals(code))
		{
			session.removeAttribute("imgCode");
			//验证登录信息
			if(email!=null && !email.equals(""))
			{
				condMap.put("email", email);
				//根据email从数据库中查询管理员信息
				Admin admin = this.userService.findOneAdmin(condMap);
				if(admin!=null)
				{
					//验证密码
					if(this.encryPasswordUtil.checkPassword(password, admin.getPassword()))
					{
						
						//验证状态
						if(admin.getStatus()==1)
						{
							//登录成功时，先把该管理员上次登录时间从数据库中取出,存入session作用域中
							session.setAttribute("lastLoginTime", admin.getLastLoginTime());
							//然后在数据库中更新管理员上次登录时间
							admin.setLastLoginTime(new Date());
							this.userService.updateOneAdmin(admin);
							session.setAttribute("admin", admin);
							return "redirect:/back/admin/index.htm";
						}else
						{
							this.info="用户被禁用";
						}
					}else
					{
						this.info="密码不正确";
					}
				}else{
					this.info="邮箱不正确";
				}
			}else
			{
				this.info="邮箱不存在";
			}
		}else
		{
			this.info="验证码不正确";
		}
		req.setAttribute("info", info);
		return this.adminLogin(req);
	}
}
